using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using XcoAppSpaces.Core;
using XcoAppSpaces.Core.Ports;
using testServer.XcoAppSpaces.Core;

namespace testApp.XcoAppSpaces.Core
{
	[Activity (Label = "testApp.XcoAppSpaces.Core", MainLauncher = true)]
	public class MainActivity : ListActivity
	{
		private int count = 1;
		private IXcoAppSpace space;
		private PCompactWorker worker;
		private Port<string> responsePort;

		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Set our view from the "main" layout resource
			SetContentView (Resource.Layout.Main);

			//initialize appspace and list view
			space = new XcoAppSpace("tcp.port=0;tcp.key=MagINet2005");
			var evtList = new EventListAdapter(this);
			ListAdapter = evtList;
			evtList.Add ("AppSpace is Running...");
			
			// Get our button from the layout resource,
			// and attach an event to it
			var button = FindViewById<Button>(Resource.Id.myButton);
			button.Click += delegate
				{
					InitWorkerAndResponsePort(evtList);

					var msg = new CompactRequest {Msg = "Request " + count++, ResponsePort = responsePort};
					worker.Post(msg);
					evtList.Add("Sent: " + msg.Msg);
					evtList.NotifyDataSetChanged();
				};
		}

		private void InitWorkerAndResponsePort(EventListAdapter evtList)
		{
			if (worker == null)
			{
				worker = space.ConnectWorker<PCompactWorker>("192.168.101.85:8000/myworker");
				responsePort = new Port<string>(
					r => RunOnUiThread(() =>
						{
							evtList.Add("Response received: " + r);
							evtList.NotifyDataSetChanged();
						}));
			}
		}

		protected override void OnDestroy()
		{
			space.Dispose();
			base.OnDestroy();
		}
	}
}


